
#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "InetAddr.hpp"
#include "Log.hpp"
enum error
{
    SOCKET_ERR = 1,
    BIND_ERR,
    USAGE_ERR,

};
class UdpServer
{
    using func_t = std::function<void(int sockfd, std::string message, InetAddr who)>;

public:
    UdpServer(uint16_t port, func_t func) : _port(port), _func(func), _sockfd(-1)
    {
    }
    void InitServer()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error,%d,%s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
        LOG(INFO, "create socket success,socket:%d", _sockfd);

        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error,%d,%s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        LOG(INFO, "bind success");
    }
    void StartServer()
    {
        while (true)
        {
            char message[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, message, sizeof(message) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                message[n] = 0;
                InetAddr addr(peer);
                _func(_sockfd, message, addr);
                LOG(DEBUG, "get request from[%s,%d]:%s,send to everyone success", addr.Ip().c_str(), addr.Port(), message);
            }
        }
        ThreadPool<function<void()>>::Getinstance()->Wait();
    }

private:
    int _sockfd;
    uint16_t _port;
    func_t _func;
};